package com.afs.electronicforensics.adapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.afs.electronicforensics.activity.ShowActivity;
import com.afs.electronicforensics.adapter.viewholder.IVViewHolder;
import com.afs.electronicforensics.entity.FileInfo;
import com.afs.electronicforensics.activity.R;
import com.afs.electronicforensics.monitor.FileModMonitorEditText;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.FileTypeUtil;
import com.afs.electronicforensics.utils.OssManager;
import com.bumptech.glide.Glide;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class AlbumCloudAdapter extends RecyclerView.Adapter<IVViewHolder>{
    private ArrayList<FileInfo> items;
    private MyItemClickListener listener;
    private View view;
    private Context context;
    private Dialog dialog;
    protected boolean isScrolling = false;


    public AlbumCloudAdapter(Context context, ArrayList<FileInfo> items) {
        this.context=context;
        this.items = items;
    }


    @NonNull
    @NotNull
    @Override
    public IVViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        view= LayoutInflater.from(parent.getContext()).inflate(R.layout.iv_item,parent,false);
        IVViewHolder holder = new IVViewHolder(view,listener);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull IVViewHolder holder, int position) {
        FileInfo currentItem=items.get(position);

        if (!TextUtils.isEmpty(currentItem.getUrl()) && !isScrolling) {
            // 这里可以用Glide等网络图片加载库
            Glide.with(view).load(currentItem.getUrl()).into(holder.imageView);
        } else {
            Glide.with(view).load(R.drawable.loading).into(holder.imageView);
        }
        holder.textView.setText(currentItem.getTitle());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new Dialog(context,R.style.Dialog_Fullscreen);
                LayoutInflater inflater = LayoutInflater.from(context);
                view = inflater.inflate(R.layout.image_dialog, null);
                dialog.setContentView(view);
                dialog.create();
                dialog.show();

                ImageView iv = view.findViewById(R.id.my_image);

                EditText imageName = view.findViewById(R.id.image_name);
                EditText imageRemark = view.findViewById(R.id.image_remark);

                TextView upDown = view.findViewById(R.id.image_up_down);
                TextView modify = view.findViewById(R.id.image_modify);
                TextView delete = view.findViewById(R.id.image_delete);
                TextView cancel = view.findViewById(R.id.image_cancel);

                modify.setVisibility(View.VISIBLE);
                Glide.with(view).load(currentItem.getUrl()).into(iv);
                String oldName = currentItem.getTitle().substring(0,currentItem.getTitle().indexOf("."));
                String oldRemark = currentItem.getRemark();

                imageName.setText(oldName);
                imageRemark.setText(oldRemark);
                upDown.setText("下载");
                upDown.setEnabled(true);
                upDown.setTextColor(Color.parseColor("#88BEF5"));

                new FileModMonitorEditText().SetMonitorEditText(modify,imageName,imageRemark,oldName,oldRemark);


                upDown.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String SDPATH = Environment.getExternalStorageDirectory() + "/";
                        OssManager.getInstance().init(view.getContext()).download(currentItem.getTitle(),currentItem.getUrl(),SDPATH);
                        Toast.makeText(context,"下载成功",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                modify.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(context,"修改成功",Toast.LENGTH_SHORT).show();
                        String name = imageName.getText().toString().trim();
                        String content = imageRemark.getText().toString().trim();
                        //获取文件后缀名
                        String substring =currentItem.getTitle().substring(currentItem.getTitle().lastIndexOf(".") + 1);
                        String upDataUrl = Constants.URL_ROOT + "file/updateMessage?content=" + content +"&id="
                                +currentItem.getId()+"&type=2"+"&upName="+name+"."+substring+"&userId="+Constants.USER_ROOT.getUid();
                        new DoUpDataMessage().execute(upDataUrl);
                        dialog.dismiss();
                    }
                });
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        items.remove(currentItem);
                        notifyDataSetChanged();
                        OssManager.getInstance().init(view.getContext()).delete(currentItem.getTitle(),2, Constants.USER_ROOT.getUid());
                        Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    public void setScrolling(boolean scrolling) {
        isScrolling = scrolling;
    }


    public void setOnItemClickListener(MyItemClickListener listener) {
        this.listener = listener;
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    private class DoUpDataMessage extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
                String info = o.toString().trim();
            try {
                if(o!=null){
                    JSONObject jo = new JSONObject(info);
                    if("1".equals(jo.getString("code"))) {
                        Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(context,"修改失败",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(context,"修改失败",Toast.LENGTH_SHORT).show();
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
            }

        }


}

